
var picInput = $('input[name="pic"]');
var fileInput = new moxie.file.FileInput({
    browse_button: 'uploadBtn',
    accept: [{title: "Images", extensions: "jpg,gif,png"}]
});

function renderFile(file) {
    var ulRef = document.getElementById('showPic');
    var liRef = document.createElement('li');
    //liRef.innerHTML = '<span class="preview"></span><span class="name">' + file.name + '</span><span class="size">, ' + file.size + ' bytes</span>';
    liRef.innerHTML = '<span class="preview"></span>';
    var thumb = liRef.getElementsByClassName('preview');
    if(typeof(file) === "string") {
        file = 'http://img.owenxh.top/' + file;
        var imgNode = document.createElement('img');
        imgNode.src = file;
        imgNode.style = 'width:50px;height:50px;';
        thumb[0].appendChild(imgNode);
    } else {
        var img = new moxie.image.Image();
        img.onload = function () {
            this.embed(thumb[0], {width: "50", height: "50", preserveHeaders: false});
        };
        console.log('typeof(file)=' + typeof(file));
        img.load(file);
    }
    ulRef.innerHTML = '';
    ulRef.appendChild(liRef);
}

function uploadFile(file) {
    var ajaxbg = $("#background,#progressBar");
    ajaxbg.show();
    var uploadUrl = '<%=request.getContextPath()%>/back/upload/uploadFiles;jsessionid=<%=session.getId()%>';
    var xhr = new moxie.xhr.XMLHttpRequest();
    var formData = new moxie.xhr.FormData();
    xhr.open("post", uploadUrl);
    formData.append('Filedata', file);
    xhr.send(formData);
    xhr.upload.addEventListener('progress', function (stat) {
        var p = document.createElement('p');
        //console.log(stat.loaded, stat.total);
        p.innerHTML = [ new Date().toString().split(' ')[4], file.name, parseInt(stat.loaded * 100 / stat.total) + '%' ].join(' ');
        document.body.appendChild(p);
    });
    //console.log(xhr);
    xhr.onreadystatechange = function (e) {
        //console.log(e);
        if (e.target.readyState === 4 && e.target.status === 200) {
            var json = e.target.responseText;
            var dataList = JSON.parse(json);
            //[{"filepath":"/files/2017-11-08/19cca7ce-45ea-44a3-b832-beaec53a77e9.png","filename":"222.png","suffix":".png","flag":"null"}]
            if (dataList === null || dataList === undefined || dataList.length <= 0) return false;
            //console.log(dataList[0].filepath);
            $('input[name="pic"]').val(dataList[0].filepath);
        } else {
            alert('上传错误');
            return false;
        }
        ajaxbg.hide();
        return true;
    };
}

fileInput.onchange = function (e) {
    var value = picInput.val();
    if (value !== undefined && value !== '') {
        if (!confirm('多次上传以最后一次上传有效')) {
            return false;
        }
    }
    e.target.files.forEach(function (file) {
        uploadFile(file);
        renderFile(file);
    });
};
fileInput.init();
